package com.walkline.screen;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.FullScreen;
import net.rim.device.api.ui.extension.component.PictureScrollField;
import net.rim.device.api.ui.extension.component.PictureScrollField.HighlightStyle;
import net.rim.device.api.ui.extension.component.PictureScrollField.ScrollEntry;

import com.walkline.util.Enumerations.RefreshAction;
import com.walkline.util.Function;
import com.walkline.util.ui.StatusListStyleButtonField;
import com.walkline.weibo.WeiboSDK;
import com.walkline.weibo.inf.Status;
import com.walkline.weibo.inf.User;

public class ShowPreviewImagesFullScreen extends FullScreen
{
	private WeiboSDK _weibo;
	private User _user;
	private Status _status;
	private Status _retweeted;
	private PictureScrollField _pictureScrollField;
	private ScrollEntry[] _entries;
	private static Bitmap STANDARD = Bitmap.getBitmapResource("status_image_single.png");
	private Bitmap[] _middleBitmaps;
	private Bitmap[] _smallBitmaps;
	private BitmapField _avatarField;
	private BitmapField _gifField;
	private String[] image_urls = null;

	public ShowPreviewImagesFullScreen(WeiboSDK weibo, User user)
	{
		super(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL | NO_SYSTEM_MENU_ITEMS);

		_weibo = weibo;
		_user = user;

		_avatarField = new BitmapField(user.getAvatarIconData() != null ? Bitmap.createBitmapFromBytes(user.getAvatarIconData(), 0, -1, 1) : Bitmap.getBitmapResource("avatar.png"), LabelField.VCENTER | LabelField.HCENTER);
		add(_avatarField);

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run() {getImage(_user.getAvatarHd());}
		});
	}

	public ShowPreviewImagesFullScreen(WeiboSDK weibo, StatusListStyleButtonField item)
	{
		_weibo = weibo;
		_status = item.getStatus();
		_retweeted = item.getRetweetedStatus();

		boolean hasStatusImage = _status.getPicUrls().getMiddlePics() != null;
		boolean hasRetweetedImage = _retweeted != null ? _retweeted.getPicUrls().getMiddlePics() != null : false;

		if (hasStatusImage)
		{
			int count = _status.getPicUrls().getCount();
			image_urls = new String[count];
			image_urls = _status.getPicUrls().getMiddlePics();

			_smallBitmaps = new Bitmap[count];
			_middleBitmaps = new Bitmap[count];
			_entries = new ScrollEntry[count];
			for (int i=0; i<count; i++)
			{
				_smallBitmaps[i] = Bitmap.getBitmapResource("status_image_single.png");
		        _entries[i] = new ScrollEntry(_smallBitmaps[i], null, null);
			}

			if (item.getStatusImageData(0) != null)
			{
				_smallBitmaps[0] = Bitmap.createBitmapFromBytes(item.getStatusImageData(0), 0, -1, 1);	
			}
		} else if (hasRetweetedImage) {
			int count = _retweeted.getPicUrls().getCount();
			image_urls = new String[count];
			image_urls = _retweeted.getPicUrls().getMiddlePics();

			_smallBitmaps = new Bitmap[count];
			_middleBitmaps = new Bitmap[count];
			_entries = new ScrollEntry[count];
			for (int i=0; i<count; i++)
			{
				_smallBitmaps[i] = Bitmap.getBitmapResource("status_image_single.png");
				_entries[i] = new ScrollEntry(_smallBitmaps[i], null, null);
			}

			if (item.getRetweetedImageData(0) != null)
			{
				_smallBitmaps[0] = Bitmap.createBitmapFromBytes(item.getRetweetedImageData(0), 0, -1, 1);	
			}
		}

		_pictureScrollField = new PictureScrollField(Display.getWidth(), Display.getHeight());
		_pictureScrollField.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				if (context == PictureScrollField.CONTEXT_CHANGE_SELECTION)
				{
					if (_entries[_pictureScrollField.getCurrentImageIndex()].getPicture().equals(STANDARD))
					{
						getImage(image_urls[_pictureScrollField.getCurrentImageIndex()]);
					}
				}
			}
		});

        _pictureScrollField.setData(_entries, 0);        
        _pictureScrollField.setHighlightStyle(HighlightStyle.NO_HIGHLIGHT);
        _pictureScrollField.setLabelsVisible(false);
        add(_pictureScrollField);

        _entries[0].setPicture(_smallBitmaps[0]);

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run() {getImage(image_urls[0]);}
		});
	}

	private void getImage(final String url)
	{
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, url, RefreshAction.USERAVATARHD);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				byte[] data = popupScreen.getImageData();

				if (popupScreen != null) {popupScreen = null;}
				if (data != null) {showImage(data);}				
			}
		});
	}

	private void showImage(byte[] data)
	{
		if (_avatarField != null)
		{
			_avatarField.setBitmap(Function.bestFit(EncodedImage.createEncodedImage(data, 0, -1), Display.getWidth(), Display.getHeight()));
		} else {
			EncodedImage image = EncodedImage.createEncodedImage(data, 0, -1);

			if (image.getImageType() == EncodedImage.IMAGE_TYPE_GIF)
			{
				_gifField = new BitmapField(null, LabelField.VCENTER | LabelField.HCENTER);
				_gifField.setImage(image);

				if (_gifField.getManager() == null)
				{
					try {
						delete(_pictureScrollField);						
					} catch (Exception e) {
					} finally {
						add(_gifField);						
					}
				}
			} else {
				_middleBitmaps[_pictureScrollField.getCurrentImageIndex()] = image.getBitmap();
				_entries[_pictureScrollField.getCurrentImageIndex()].setPicture(Function.bestFit(image, Display.getWidth(), Display.getHeight()));

				if (_pictureScrollField.getManager() == null)
				{
					try {
						delete(_gifField);	
					} catch (Exception e) {
					} finally {
						add(_pictureScrollField);						
					}
				}
			}
		}
	}

    protected boolean navigationClick(int status, int time)
    {
    	if (_pictureScrollField != null)
    	{
            if (_pictureScrollField.isFocus())
            {
            	int count = _pictureScrollField.getCurrentImageIndex();
            	UiApplication.getUiApplication().pushScreen(new ShowPreivewImageFullScreen(_weibo, image_urls[count], _middleBitmaps[count]));

                return true;
            }    		
    	}

        return super.navigationClick(status, time);
    }

    protected boolean touchEvent(TouchEvent message)
    {
        if (message.getEvent() == TouchEvent.CLICK)
        {
        	if (_pictureScrollField != null)
        	{
                if (_pictureScrollField.isFocus())
                {
                	int count = _pictureScrollField.getCurrentImageIndex();
                	UiApplication.getUiApplication().pushScreen(new ShowPreivewImageFullScreen(_weibo, image_urls[count], _middleBitmaps[count]));
                }

                return true;
        	}
        }

        return super.touchEvent(message);
    }

	public boolean onClose()
	{
		UiApplication.getUiApplication().popScreen(this);

		return true;
	}

	protected boolean onSavePrompt() {return true;}
}